package com.yupi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.model.entity.UserInterfaceInfo;
import com.yupi.project.service.UserInterfaceInfoService;
import com.yupi.project.mapper.UserInterfaceInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

/**
* @author 11818
* @description 针对表【user_interface_info(用户接口调用关系表)】的数据库操作Service实现
* @createDate 2024-04-27 17:49:09
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService{

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean b) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 创建时，所有参数必须非空
        //校验参数
        if (b) {
            if (userInterfaceInfo.getInterfaceInfoId() <= 0 || userInterfaceInfo.getUserId() <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口或者用户不存在");
            }
        }
    }

    //TODO 分布式锁redis实现
    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ)
    public boolean invokeCount(long interfaceInfoId, long userId) {
        //分布式锁和 独占锁
        if(interfaceInfoId <= 0 || userId <= 0) throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数错误");
        UpdateWrapper<UserInterfaceInfo> userInterfaceInfoUpdateWrapper = new UpdateWrapper<>();
        userInterfaceInfoUpdateWrapper.eq("interfaceInfoId",interfaceInfoId).eq("userId",userId).gt("leftNum",0).setSql("leftNum = leftNum - 1,totalNum = totalNum + 1");
        return  this.update(userInterfaceInfoUpdateWrapper);
    }

}




